/*   
 * Copyright (c) 2010-2020 DMGIS Ltd. All Rights Reserved.   
 *   
 * This software is the confidential and proprietary information of   
 * DMGIS. You shall not disclose such Confidential Information   
 * and shall use it only in accordance with the terms of the agreements   
 * you entered into with DMGIS.   
 *   
 */
package com.dmgis.qxfw.dataservice.bigdata.service.impl;


import com.dmgis.qxfw.dataservice.bigdata.service.IInteractionService;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.location_log;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.vistor_upload_pictemp;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CzStation;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.PicInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.TourStaInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.util.DateTime;
import com.dmgis.qxfw.dataservice.businessservice.common.util.FileUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.JsonUtil;
import com.dmgis.qxfw.dataservice.businessservice.common.util.StringUtil;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("InteractionSerices")
public class InteractionServiceImpl implements IInteractionService {

	private  final String operatingSystem;

	@Autowired
	public InteractionServiceImpl(String operatingSystem) {
		this.operatingSystem = operatingSystem;
	}
	ProcessRequestController pc = new ProcessRequestController();
	@Override
	public String UploadPicPath(String urlPath, String localPath) {
		int bflag = 0;
		try {
			List<vistor_upload_pictemp> vistor_upload_pictemps = new ArrayList<vistor_upload_pictemp>();
			String date = DateTime.now().toDateTimeString();
			vistor_upload_pictemp temp = new vistor_upload_pictemp();
			temp.setImagepath(urlPath);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			temp.setTime(sdf.parse(date));
			vistor_upload_pictemps.add(temp);
			Map<String, String> insertParam = new HashMap<String, String>();
			RequestDataByInsert<vistor_upload_pictemp> insertRequest = new RequestDataByInsert<vistor_upload_pictemp>();
			insertRequest.setData(vistor_upload_pictemps);
			insertParam.put("method", "vistor_upload_pic");
			insertParam.put("advCode", DbConfig.advCode);
			insertParam.put("sqlType", "insert");
			insertParam.put("param", JsonUtil.object2Json(insertRequest));
			String result = pc.processRequest(insertParam);
			bflag=Integer.parseInt(result);
			try {
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			// 入库mongo数据库
			//MongoService1 mongoService = new MongoService1();
			FileRequestService mongoService = new FileRequestService();
			File input = new File(localPath);

			byte[] bytes = FileUtil.fileToBytes(input.getAbsolutePath());
			Map<String,Object> map = new HashMap<>();
			map.put("collectionName","image_file");
			map.put("table_name","vistor_upload_pic");
			map.put("id",bflag);
			map.put("advCode",DbConfig.advCode);
			map.put("data",bytes);
			int s = mongoService.insertData(map);
			if (s==1) {
				System.out.println("data was updated");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return String.valueOf(bflag);
	}

	@Override
	public String UpDateTextInfo(String city, String flag, String fileName, String scaleWH) {
		String success = "0";
		try {
			vistor_upload_pictemp temp = new vistor_upload_pictemp();
			temp.setPosition(city);
			temp.setImagepath(fileName);
			temp.setScalewh(Double.parseDouble(scaleWH));

			RequestDataByUpdate<String, vistor_upload_pictemp> updateRequest = new RequestDataByUpdate<String, vistor_upload_pictemp>();
			updateRequest.setParam(String.format("id='"+flag+"'"));
			updateRequest.setData(temp);
			Map<String, String> updateParam = new HashMap<String, String>();
			updateParam.put("method", "vistor_upload_pic");
			updateParam.put("advCode",DbConfig.advCode);
			updateParam.put("sqlType", "update");
			updateParam.put("param", JsonUtil.object2Json(updateRequest));
			String result = pc.processRequest(updateParam);//DbConfig.ZYURL

			int bflag =Integer.parseInt(result) ;
			success = bflag > 0 ? String.valueOf(bflag) + "|上传成功" : String.valueOf(bflag) + "|上传失败";
		} catch (Exception ex) {
			ex.printStackTrace();
			success = "0" + ex.getMessage();
		}
		return success;
	}

	@Override
	public String DelPicById(String Id) {
		String result = "";
		try {
			RequestDataByDelete<String> DataByDelete = new RequestDataByDelete<String>();
			DataByDelete.setParam(String.format("Id='%s'", Id));
			Map<String,String> map=new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(DataByDelete));
			map.put("method","vistor_upload_pic");
			map.put("advCode",DbConfig.advCode);
			map.put("sqlType", "delete");
			result = pc.processRequest(map);
			if (result.equals("")){
				result="[]";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	@Override
	public String UpDateStaSurvey(String type, String text) {
		String date = DateTime.now().toDateTimeString();
		int bFlag = 0;
		String strSql = String.format("INSERT INTO stasurvey (type,time,text) VALUES ('%s','%s','%s') RETURNING id",
				type, date, text);
		try {
		} catch (Exception ex) {

			throw ex;
		}
		return String.valueOf(bFlag);
	}

	@Override
	public List<PicInfo> getPicture(String urlPath, String localPath) {
		List<PicInfo> result1 = new ArrayList<PicInfo>();
		try {
			RequestDataBySelect dataBySelect=new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"ID,ImagePath,Time,Position,ScaleWH"});
			dataBySelect.setSort(new String[]{"ID desc"});
			dataBySelect.setLimit(10);
			Map<String,String> map=new HashMap<String,String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method","vistor_upload_pic");
			map.put("advCode",DbConfig.advCode);
			map.put("sqlType","select");
			String result = pc.processRequest(map);
			if (result.equals("")){
				result="[]";
			}
			List<vistor_upload_pictemp> pictemp = new ArrayList<>();
			pictemp =JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<vistor_upload_pictemp>>() {});
			for (vistor_upload_pictemp temp:pictemp) {
				PicInfo info = new PicInfo();
				info.setId(temp.getId().toString());
				info.setPicUrl(temp.getImagepath());
				info.setTime(new DateTime(temp.getTime()).toDateTimeString());
				result1.add(info);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result1;
	}

	@Override
	public List<PicInfo> getPictureByID(String urlPath, String localPath, String id) {
		List<PicInfo> result1 = new ArrayList<PicInfo>();
		try {
			RequestDataBySelect dataBySelect=new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"ID,ImagePath,Time,Position,ScaleWH"});
			dataBySelect.setParam("ID='"+id+"'");
			dataBySelect.setSort(new String[]{"ID desc"});
			dataBySelect.setLimit(10);
			Map<String,String> map=new HashMap<String,String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method","vistor_upload_pic");
			map.put("advCode",DbConfig.advCode);
			map.put("sqlType","select");
			String result = pc.processRequest(map);
			if (result.equals("")){
				result="[]";
			}
			List<vistor_upload_pictemp> pictemp = new ArrayList<>();
			pictemp =JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<vistor_upload_pictemp>>() {});
			for (vistor_upload_pictemp temp:pictemp) {
				PicInfo info = new PicInfo();
				info.setId(temp.getId().toString());
				info.setPicUrl(temp.getImagepath());
				info.setPosition(temp.getPosition());
				info.setScaleWH(temp.getScalewh().toString());
				info.setTime(new DateTime(temp.getTime()).toDateTimeString() );
				result1.add(info);
			}
			for (PicInfo picInfo : result1) {
				String PhysicUrl = localPath + picInfo.getId() + ".png";
				String httpUrl = urlPath + picInfo.getId() + ".png";
				// 当图片上传url存在并且图片review url不存在时,mongodb下载
				File file = new File(PhysicUrl);
				if (!file.exists()) {
				}
				picInfo.setPicUrl(httpUrl);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result1;
	}

	@Override
	public ArrayList<Object> GetOrderPageInfo(String code, HttpServletRequest request) {
		String openId = "sunshine";// 测试
		WeatherForecastServiceImpl fcst = new WeatherForecastServiceImpl(operatingSystem);
		ArrayList<Object> arr = new ArrayList<Object>();
		ArrayList<Object> arrTemp = new ArrayList<Object>();
		/// 所有景点和实景监控点信息
		arrTemp = fcst.getAllTourStaInfo();
		arr.add(arrTemp);
		// 定制信息
		try {
			RequestDataBySelect dataBySelect=new RequestDataBySelect();
			dataBySelect.setColumns(new String[]{"OrderCity,OrderWarning"});
			dataBySelect.setParam("AppId='" + openId + "'");
			Map<String,String> map=new HashMap<String, String>();
			map.put("param", JsonUtil.object2Json(dataBySelect));
			map.put("method","location_log");
			map.put("advCode",DbConfig.advCode);
			map.put("sqlType", "select");
			String result = pc.processRequest(map);
			if (result.equals("")){
				result="[]";
			}
			List<HashMap<String, Object>> dt =JsonUtil.jsonStr2TypeReference(result, new TypeReference<List<HashMap<String, Object>>>() {});


			for (HashMap<String, Object> map1 : dt) {
				{
					String orderCity = map1.get("ordercity") == null ? "" : map1.get("ordercity").toString();
					String orderWarning = map1.get("orderwarning") == null ? "" : map1.get("orderwarning").toString();
					arr.add(orderCity);/// 定制城市
					arr.add(orderWarning);// 定制预警
					arrTemp = new ArrayList<Object>();
					DateTime date = DateTime.now();
					String[] tourList = orderCity.split("&");
					for (String tourName : tourList) {
						if (!tourName.equals("")) {
							TourStaInfo staInfo = fcst.getTourInfo(tourName,request);
							CzStation[] tourFcstInfo = fcst.getTourInfoList(date.toDateString(),
									date.GetHour() >= 8 && date.GetHour() < 20 ? "08" : "20", staInfo.getId());
							arrTemp.add(tourFcstInfo);
						}
					}
					arr.add(arrTemp);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return arr;
	}

	@Override
	public String SaveOrderChange(String openId, String orderCity, String orderWarning) {
		openId = "sunshine";// 测试
		String result = "";
		try {
			location_log log = new location_log();

			int flag = 0;
			String updateParam1 = "", updateParam2 = "", updateParam = "";
			if (!StringUtil.IsNullOrEmpty(orderCity)) {
				updateParam1 += String.format("%s", orderCity);
				log.setOrdercity(updateParam1);
			}
			if (!StringUtil.IsNullOrEmpty(orderWarning)) {
				updateParam2 += String.format("%s", orderWarning);
				log.setOrderwarning(updateParam2);
			}
			if (!updateParam1.equals(updateParam2)) {
				updateParam += updateParam1 + "," + updateParam2;
				if (updateParam.equals(",") || updateParam2.equals("")) {
					updateParam = StringUtil.trimEnd(updateParam, ',');
				} else {
					updateParam = StringUtil.trimStart(updateParam, ',');

					log.setOrderwarning(updateParam2);
				}
			}
			if (StringUtil.IsNullOrEmpty(updateParam)) {
				return "0";
			}

			RequestDataByUpdate<String, location_log> updateRequest = new RequestDataByUpdate<String, location_log>();
			updateRequest.setParam(String.format("AppId='"+openId+"'"));
			updateRequest.setData(log);
			Map<String, String> update = new HashMap<String, String>();
			update.put("method", "location_log");
			update.put("advCode",DbConfig.advCode);
			update.put("sqlType", "update");
			update.put("param", JsonUtil.object2Json(updateRequest));
			result = pc.processRequest(update);//DbConfig.ZYURL

			flag =Integer.parseInt(result) ;
			result = String.valueOf(flag);
		} catch (Exception ex) {
			ex.printStackTrace();
			return ex.getMessage();
		}
		return result;
	}

}
